package com.example.financialsystem.fragment;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.financialsystem.MainActivity;
import com.example.financialsystem.R;
import com.example.financialsystem.adapter.RecyclerStatisticsAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import models.Book;
import models.StatisticInfo;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import others.ServerResponse;

import static android.content.Context.NOTIFICATION_SERVICE;
import static androidx.constraintlayout.widget.Constraints.TAG;
import static others.Const.CURRENT_BOOK;
import static others.Const.IP;
import static others.Const.PORT;
import static others.Const.currentBook;
import static others.Const.currentUserVo;
import static others.Const.isVisible;
import static others.Tools.ToastShow;
import static utils.GsonUtil.Json2Class;
import static utils.GsonUtil.String2ListStatisticServerResponse;

public class BookDetailFragment extends Fragment implements View.OnClickListener {

    private RecyclerView bookDetailRecyclerView;
    private List<StatisticInfo> detailOptionList = new ArrayList<>();
    private String responseDate;
    private Book book;
    private RecyclerStatisticsAdapter adapter;
    private TextView textSurplus;
    private TextView textMonthIncome;
    private TextView month;
    public static final int UPDATE_STATISTIC = 1;
    public static final int UPDATE_BUDGET = 2;

    private ImageView imageVisible;
    private double monthOutcome;
    private double monthIncome;
    private LinearLayout bookBackground;
    private TextView buttonBudget;

    private double money;

    private DecimalFormat df = new DecimalFormat("######0.00");

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_details, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        book = (Book) bundle.getSerializable(CURRENT_BOOK);

        bookBackground = (LinearLayout)getActivity().findViewById(R.id.book_background_layout);
        if (book.getType() == 1){
            bookBackground.setBackgroundResource(R.drawable.background_family);
        }

        bookDetailRecyclerView = (RecyclerView)getActivity().findViewById(R.id.book_detail_recyclerView);

        getInformationFromServer();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        bookDetailRecyclerView.setLayoutManager(layoutManager);

        textSurplus = (TextView)getActivity().findViewById(R.id.book_month_surplus);
        textMonthIncome = (TextView)getActivity().findViewById(R.id.book_month_income);
        imageVisible = (ImageView)getActivity().findViewById(R.id.book_money_visible);
        imageVisible.setOnClickListener(this);

        month = (TextView)getActivity().findViewById(R.id.this_month);
        Calendar calendar = Calendar.getInstance();
        month.setText(calendar.get(Calendar.MONTH)+1+"");

        buttonBudget = (TextView)getActivity().findViewById(R.id.book_budget);
        if (currentBook.getBudget() == -1){
            buttonBudget.setText("暂无预算");
        } else {
            buttonBudget.setText(df.format(currentBook.getBudget())+"");
        }
        buttonBudget.setOnClickListener(this);
    }

    public void simulate(){
        StatisticInfo model1 = new StatisticInfo("今天",0,"还没有记过帐",800,1300);
        StatisticInfo model2 = new StatisticInfo("本周",1,"3.23-3.29",800,1300);
        StatisticInfo model3 = new StatisticInfo("本月",2,"3.1-3.31",800,1300);
        StatisticInfo model4 = new StatisticInfo("今年",3,"2020年",800,1300);
        detailOptionList.add(model1);
        detailOptionList.add(model2);
        detailOptionList.add(model3);
        detailOptionList.add(model4);
    }

    public void getInformationFromServer(){
        String url = "http://" + IP + ":" + PORT + "/portal/SumStatistic.do";
        RequestBody requestBody = new FormBody.Builder()
                .add("bookId",book.getId())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = client.newCall(request).execute();
                    responseDate = response.body().string();
                    Message message = new Message();
                    message.what = UPDATE_STATISTIC;
                    handler.sendMessage(message);
                }catch (Exception e){
                    e.printStackTrace();
                    Looper.prepare();
                    ToastShow("我们好像遇到了一些问题1");
                    Looper.loop();
                }
            }
        }).start();
    }

    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case UPDATE_STATISTIC:
                    try {
                        ServerResponse<List<StatisticInfo>> serverResponse = String2ListStatisticServerResponse(responseDate);
                        if (serverResponse.getStatus() == 0){
                            detailOptionList.clear();
                            detailOptionList = serverResponse.getData();
                            StatisticInfo monthInfo = detailOptionList.get(2);
                            adapter = new RecyclerStatisticsAdapter(detailOptionList);
                            bookDetailRecyclerView.setAdapter(adapter);
                            monthOutcome = monthInfo.getOutcome();
                            monthIncome = monthInfo.getIncome();
                            if (isVisible) {
                                setTitleMoney(monthOutcome+"",monthIncome+"");
                            }
                        }else {
                            ToastShow("我们好像遇到了一些问题2");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        ToastShow("抱歉，可能出了一些意外3");
                    }
                    break;
                case UPDATE_BUDGET:
                    ServerResponse serverResponse = Json2Class(responseDate);
                    if (serverResponse.getStatus() == 0){
                        ToastShow("设置预算成功");
                        buttonBudget.setText(df.format(money)+"");
                    } else {
                        ToastShow(serverResponse.getMsg()+"(BookDetailFragment)");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public void setTitleMoney(String surplus,String income){
        textSurplus.setText(surplus + "");
        textMonthIncome.setText(income + "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.book_money_visible:
                if (isVisible){
                    imageVisible.setImageResource(R.drawable.conceal);
                    setTitleMoney("******","******");
                }else{
                    imageVisible.setImageResource(R.drawable.display);
                    setTitleMoney(monthOutcome+"",monthIncome+"");
                }
                isVisible = !isVisible;
                break;
            case R.id.book_budget:
                if (currentBook.getOwner().equals(currentUserVo.getId())){
                    final EditText et = new EditText(getContext());
                    et.setInputType(InputType.TYPE_CLASS_NUMBER);
                    new AlertDialog.Builder(getContext()).setTitle("设置账本新预算")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setView(et)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String input = et.getText().toString();
                                    money = Double.valueOf(input);
                                    if (money > 0) {
                                        updateBudget(money);
                                    }
                                    else {
                                        ToastShow("请输入正确数值");
                                    }
                                }
                            } )
                            .show();
                } else {
                    ToastShow("您无权对预算进行操作");
                }
                break;
        }
    }

    public void updateBudget(double money){
        String url = "http://" + IP + ":" + PORT + "/portal/book/updateBudget.do";
        RequestBody requestBody = new FormBody.Builder()
                .add("bookId",book.getId())
                .add("money",money+"")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = client.newCall(request).execute();
                    responseDate = response.body().string();
                    Message message = new Message();
                    message.what = UPDATE_BUDGET;
                    handler.sendMessage(message);
                }catch (Exception e){
                    e.printStackTrace();
                    Looper.prepare();
                    ToastShow("我们好像遇到了一些问题1");
                    Looper.loop();
                }
            }
        }).start();
    }

}
